<!DOCTYPE html>












  


<html class="theme-next mist use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">









  
  
  <link rel="stylesheet" media="all" href="/lib/Han/dist/han.min.css?v=3.3">




<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



















  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.lug.ustc.edu.cn/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.4.2" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.jpg?v=6.4.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.jpg?v=6.4.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.jpg?v=6.4.2">


  <link rel="mask-icon" href="/images/logo.svg?v=6.4.2" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '6.4.2',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  




  <meta name="keywords" content="笔记">
<meta property="og:type" content="article">
<meta property="og:title" content="3个小时零Python基础搭建Django项目">
<meta property="og:url" content="https://devzhao.com/post/f7443a5f.html">
<meta property="og:site_name" content="学而时习之">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://qnfile.devzhao.com/blog/2018-11-06-040643.jpg">
<meta property="og:image" content="http://qnfile.devzhao.com/blog/2018-11-06-043951.png">
<meta property="og:image" content="http://qnfile.devzhao.com/blog/2018-11-06-044643.png">
<meta property="og:image" content="http://qnfile.devzhao.com/blog/2018-11-06-044722.png">
<meta property="og:image" content="http://qnfile.devzhao.com/blog/2018-11-06-044918.png">
<meta property="og:image" content="http://qnfile.devzhao.com/blog/2018-11-06-045936.jpg">
<meta property="og:image" content="http://qnfile.devzhao.com/blog/2018-11-06-050421.png">
<meta property="og:image" content="http://qnfile.devzhao.com/blog/2018-11-06-051452.png">
<meta property="og:image" content="http://qnfile.devzhao.com/blog/2018-11-06-053742.png">
<meta property="og:image" content="http://qnfile.devzhao.com/blog/2018-11-06-055345.png">
<meta property="og:image" content="http://qnfile.devzhao.com/blog/2018-11-06-063518.png">
<meta property="og:image" content="http://qnfile.devzhao.com/blog/2018-11-06-063954.png">
<meta property="og:updated_time" content="2018-11-07T15:04:59.688Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="3个小时零Python基础搭建Django项目">
<meta name="twitter:image" content="http://qnfile.devzhao.com/blog/2018-11-06-040643.jpg">






  <link rel="canonical" href="https://devzhao.com/post/f7443a5f.html"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>3个小时零Python基础搭建Django项目 | 学而时习之</title>
  






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?b8fcd96e6d9e134b3c9551097ed074a4";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  <div id="showImgFullScrn" style="display: none;"><img id="showImgFullScrnImg" src="" style="max-height:100%"></div>

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">学而时习之</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">时间就是力量</h1>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-shortcut">
    <a href="/shortcut/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-shirtsinbulk"></i> <br />快捷</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  
    

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://devzhao.com/post/f7443a5f.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zhaohan">
      <meta itemprop="description" content="教，是最好的学">
      <meta itemprop="image" content="http://qnfile.devzhao.com/blog/2018-10-12-125720.jpg#/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="学而时习之">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">3个小时零Python基础搭建Django项目
              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-11-06 12:05:47" itemprop="dateCreated datePublished" datetime="2018-11-06T12:05:47+08:00">2018-11-06</time>
            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/python/" itemprop="url" rel="index"><span itemprop="name">python</span></a></span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/post/f7443a5f.html#comments" itemprop="discussionUrl">
                  <span class="post-meta-item-text">评论数：</span> <span class="post-comments-count valine-comment-count" data-xid="/post/f7443a5f.html" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/post/f7443a5f.html" class="leancloud_visitors" data-flag-title="3个小时零Python基础搭建Django项目">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数：</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-symbolscount">
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">本文字数：</span>
                
                <span title="本文字数">13k</span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body han-init-context" itemprop="articleBody">

      
      

      
        <p><img class="zhao-img-h153" src="http://qnfile.devzhao.com/blog/2018-11-06-040643.jpg"></p>
<a id="more"></a>
<p>今天朋友接了一个小项目——做一个公司的官网，要求他一个人完成。找我帮忙让我帮写几个接口。于是想到前几天打算学习python来着，那么，就尝试用python来完成这个任务吧。</p>
<p>以下是从完全不懂python（但是我已经做了三年的java了）的情况下，从零开始做一个项目的过程笔记。</p>
<p>因为对于现在的我来说，python还是一个黑箱，所以这个笔记会比较乱，这个项目完成后会重新整理。</p>
<h2 id="需求分析"><a href="#需求分析" class="headerlink" title="需求分析"></a>需求分析</h2><p>需求很明确，就是一个公司的官网，除了大部分固定的内容之外，就是一个新闻系统了。</p>
<p>对于用户端来说，只要提供一个新闻列表、一个新闻详情的接口即可。</p>
<p>对于管理端来说，只需要新闻的增删改查几个接口即可。</p>
<h2 id="技术选型"><a href="#技术选型" class="headerlink" title="技术选型"></a>技术选型</h2><h3 id="了解主流的python框架"><a href="#了解主流的python框架" class="headerlink" title="了解主流的python框架"></a>了解主流的python框架</h3><p>在做java项目的时候，我们有很多可选的框架技术，比如springmvc、springboot等。那么python应该也会有相应的主流框架吧。</p>
<p>那么第一个关键字就是：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pyhon主流框架</span><br></pre></td></tr></table></figure>
<p>输入金百度，“搜索工具”中选择最近一年。看了5个搜索结果，排除掉“转载”的内容相同的，得到的结果就是“Django”</p>
<h2 id="Django"><a href="#Django" class="headerlink" title="Django"></a>Django</h2><p>根据网上的这套Django教程<a href="http://www.runoob.com/django/django-tutorial.html" target="_blank" rel="noopener">http://www.runoob.com/django/django-tutorial.html</a>,Django是一套web框架。</p>
<p>猜想，应该类似于springMvc，我需要的是restful的接口，那就看看Django能不能满足我的要求了。</p>
<p>接下来查的关键字是</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Django restful</span><br></pre></td></tr></table></figure>
<h3 id="Django实现restful"><a href="#Django实现restful" class="headerlink" title="Django实现restful"></a>Django实现restful</h3><p>看了几篇之，都是将具体的实现，终于找到一篇讲思路的</p>
<p><a href="https://blog.csdn.net/xie_0723/article/details/78219007" target="_blank" rel="noopener">https://blog.csdn.net/xie_0723/article/details/78219007</a></p>
<p>另外，作者还细心的写了“环境”，在环境里，我发现了一个不太熟悉的词“PyCharm”，那就查一下吧。</p>
<p>PyCharm是一个python的ide。</p>
<p>那太好了，有了这个ide应该就不用手动敲命令行了，效率提高了。</p>
<h3 id="PyCharm"><a href="#PyCharm" class="headerlink" title="PyCharm"></a>PyCharm</h3><p>安装好P有charm，先创建一个新项目试试看。</p>
<p>发现里面直接由Django的选项，真实贴心，不管了，先所有的按照默认选项试试吧。</p>
<p><img src="http://qnfile.devzhao.com/blog/2018-11-06-043951.png" alt=""></p>
<p>看到这个熟悉的界面，跟IntelliJ的一毛一样。玩了那么久的IntelliJ做java，那这个软件起步易如反掌。</p>
<p>按照IntelliJ的使用方式，试试看能不能把Django项目跑起来。</p>
<p>真的跑起来了。</p>
<p><img src="http://qnfile.devzhao.com/blog/2018-11-06-044643.png" alt=""></p>
<p><img src="http://qnfile.devzhao.com/blog/2018-11-06-044722.png" alt=""></p>
<h3 id="Hello-world"><a href="#Hello-world" class="headerlink" title="Hello world"></a>Hello world</h3><p>那么接下来肯定就是helloworld啦。</p>
<p>根据网上的Django教程<a href="http://www.runoob.com/django/django-tutorial.html" target="_blank" rel="noopener">http://www.runoob.com/django/django-tutorial.html</a></p>
<p><img src="http://qnfile.devzhao.com/blog/2018-11-06-044918.png" alt=""></p>
<h2 id="项目搭建"><a href="#项目搭建" class="headerlink" title="项目搭建"></a>项目搭建</h2><p>到目前为止我在没有看过python的语法的前提下已经把Django跑起来了。</p>
<p>那么接下来就要思考几个问题：</p>
<ol>
<li>restfull</li>
<li>如何连数据库，连接池问题</li>
<li>后台的管理的权限怎么办</li>
</ol>
<p>因为功能简单，加上这只是一个试水项目，所以项目构架分层什么的就不考虑了，如果按照spring的概念来说，就是直接在Controller里面读写数据库。</p>
<h3 id="restfull"><a href="#restfull" class="headerlink" title="restfull"></a>restfull</h3><p>根据 <a href="https://blog.csdn.net/xie_0723/article/details/78219007" target="_blank" rel="noopener">https://blog.csdn.net/xie_0723/article/details/78219007</a>中的结构</p>
<p><img src="http://qnfile.devzhao.com/blog/2018-11-06-045936.jpg" alt=""></p>
<table>
<thead>
<tr>
<th>错误</th>
</tr>
</thead>
<tbody>
<tr>
<td>1. 我先建一个package名为Api然后在里面建一个文件urls.py。</td>
</tr>
</tbody>
</table>
<ol>
<li>建立项目下属APP</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ django-admin startapp Api</span><br></pre></td></tr></table></figure>
<ol start="2">
<li>根据教程安装</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">(venv) zhaohandeMacBook-Pro:bhjd_newmanager zhaohan$ pip install djangorestframework</span><br><span class="line">Collecting djangorestframework</span><br><span class="line">  Downloading https://files.pythonhosted.org/packages/99/0b/d37a5a96c5d301e23adcabcc2f3fa659fb34e6308590f95ebb50cdbe98a1/djangorestframework-3.9.0-py2.py3-none-any.whl (924kB)</span><br><span class="line">    100% |████████████████████████████████| 931kB 233kB/s</span><br><span class="line">Installing collected packages: djangorestframework</span><br><span class="line">Successfully installed djangorestframework-3.9.0</span><br><span class="line">You are using pip version 10.0.1, however version 18.1 is available.</span><br><span class="line">You should consider upgrading via the &apos;pip install --upgrade pip&apos; command.</span><br><span class="line">(venv) zhaohandeMacBook-Pro:bhjd_newmanager zhaohan$ pip install markdown</span><br><span class="line">Collecting markdown</span><br><span class="line">  Downloading https://files.pythonhosted.org/packages/7a/6b/5600647404ba15545ec37d2f7f58844d690baf2f81f3a60b862e48f29287/Markdown-3.0.1-py2.py3-none-any.whl (89kB)</span><br><span class="line">    100% |████████████████████████████████| 92kB 165kB/s</span><br><span class="line">Installing collected packages: markdown</span><br><span class="line">Successfully installed markdown-3.0.1</span><br><span class="line">You are using pip version 10.0.1, however version 18.1 is available.</span><br><span class="line">You should consider upgrading via the &apos;pip install --upgrade pip&apos; command.</span><br><span class="line">(venv) zhaohandeMacBook-Pro:bhjd_newmanager zhaohan$ pip install django-filter</span><br><span class="line">Collecting django-filter</span><br><span class="line">  Downloading https://files.pythonhosted.org/packages/6a/8b/8517167a0adc45ce94d0873efb9487dd4cdeff7e10f96e837ad3d58f5837/django_filter-2.0.0-py3-none-any.whl (69kB)</span><br><span class="line">    100% |████████████████████████████████| 71kB 103kB/s</span><br><span class="line">Requirement already satisfied: Django&gt;=1.11 in ./venv/lib/python3.7/site-packages (from django-filter) (2.1.3)</span><br><span class="line">Requirement already satisfied: pytz in ./venv/lib/python3.7/site-packages (from Django&gt;=1.11-&gt;django-filter) (2018.7)</span><br><span class="line">Installing collected packages: django-filter</span><br><span class="line">Successfully installed django-filter-2.0.0</span><br><span class="line">You are using pip version 10.0.1, however version 18.1 is available.</span><br><span class="line">You should consider upgrading via the &apos;pip install --upgrade pip&apos; command.</span><br><span class="line">(venv) zhaohandeMacBook-Pro:bhjd_newmanager zhaohan$</span><br></pre></td></tr></table></figure>
<ol start="3">
<li>根据教程配置</li>
</ol>
<p>教程里只说“配置”，没有说写在哪个文件里，但是在前面的教程<a href="http://www.runoob.com/django/django-first-app.html" target="_blank" rel="noopener">http://www.runoob.com/django/django-first-app.html</a>里已经说了下面的文件是Django 项目的设置/配置，而且这里也刚好看到了 INSTALLED_APPS ，应该是这没错了。</p>
<p><img src="http://qnfile.devzhao.com/blog/2018-11-06-050421.png" alt=""></p>
<ol start="4">
<li>打开AutoApi/Api/views.py 编写如下代码</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">from django.http import JsonResponse, HttpResponseNotAllowed, HttpResponse</span><br><span class="line">from django.views.decorators.csrf import csrf_exempt</span><br><span class="line">from rest_framework.parsers import JSONParser</span><br><span class="line">from rest_framework import status</span><br><span class="line"></span><br><span class="line">@csrf_exempt</span><br><span class="line">def run_job(request):</span><br><span class="line">    # 判断请求头是否为json</span><br><span class="line">    if request.content_type != &apos;application/json&apos;:  </span><br><span class="line">        # 如果不是的话，返回405</span><br><span class="line">        return HttpResponse(&apos;only support json data&apos;, status=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE)</span><br><span class="line">    # 判断是否为post 请求</span><br><span class="line">    if request.method == &apos;POST&apos;:</span><br><span class="line">        try:</span><br><span class="line">            # 解析请求的json格式入参</span><br><span class="line">            data = JSONParser().parse(request)</span><br><span class="line">        except Exception as why:</span><br><span class="line">            print(why.args)</span><br><span class="line">        else:</span><br><span class="line">            content = &#123;&apos;msg&apos;: &apos;SUCCESS&apos;&#125;</span><br><span class="line">            print(data)</span><br><span class="line">            # 返回自定义请求内容content,200状态码</span><br><span class="line">            return JsonResponse(data=content, status=status.HTTP_200_OK)</span><br><span class="line">    # 如果不是post 请求返回不支持的请求方法</span><br><span class="line">    return HttpResponseNotAllowed(permitted_methods=[&apos;POST&apos;])</span><br></pre></td></tr></table></figure>
<ol start="5">
<li>打开bhjd_newmanager/Api/urls.py 编写如下代码</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">from django.conf.urls import url</span><br><span class="line">from Api import views</span><br><span class="line"></span><br><span class="line">urlpatterns = [</span><br><span class="line">    url(r&apos;^runJob/$&apos;,views.run_job),</span><br><span class="line">]</span><br></pre></td></tr></table></figure>
<ol start="6">
<li>打开bhjd_newmanager/bhjd_newmanager/urls.py 修改如下代码</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">ALLOWED_HOSTS = &apos;*&apos; # 修改为* 代码允许任意host</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">from django.contrib import admin</span><br><span class="line">from django.urls import path</span><br><span class="line">from django.conf.urls import url,include</span><br><span class="line"></span><br><span class="line">urlpatterns = [</span><br><span class="line">    path(&apos;admin/&apos;, admin.site.urls),</span><br><span class="line">    url(r&apos;^&apos;, include(&apos;Api.urls&apos;)),  # 新增</span><br><span class="line">]</span><br></pre></td></tr></table></figure>
<ol start="7">
<li>启动服务验证结果</li>
</ol>
<p><img src="http://qnfile.devzhao.com/blog/2018-11-06-051452.png" alt=""></p>
<p>至此restfull的问题解决了。</p>
<h3 id="如何连数据库，处理连接池问题"><a href="#如何连数据库，处理连接池问题" class="headerlink" title="如何连数据库，处理连接池问题"></a>如何连数据库，处理连接池问题</h3><p>那么接下来要查询的关键字就是“Django mysql”和“Django数据库连接池”。</p>
<h4 id="Django使用mysql"><a href="#Django使用mysql" class="headerlink" title="Django使用mysql"></a>Django使用mysql</h4><p>百度查处了这样一篇文章：</p>
<p><a href="https://www.cnblogs.com/yuyang26/p/7411269.html" target="_blank" rel="noopener">mysql 连接 django</a></p>
<p>那么开始实操吧。</p>
<h5 id="安装mysqlclient"><a href="#安装mysqlclient" class="headerlink" title="安装mysqlclient"></a>安装mysqlclient</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ pip install mysqlclient</span><br></pre></td></tr></table></figure>
<p>报错了</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">(venv) zhaohandeMacBook-Pro:bhjd_newmanager zhaohan$ pip install mysqlclient</span><br><span class="line">Collecting mysqlclient</span><br><span class="line">  Downloading https://files.pythonhosted.org/packages/ec/fd/83329b9d3e14f7344d1cb31f128e6dbba70c5975c9e57896815dbb1988ad/mysqlclient-1.3.13.tar.gz (90kB)</span><br><span class="line">    100% |████████████████████████████████| 92kB 200kB/s</span><br><span class="line">    Complete output from command python setup.py egg_info:</span><br><span class="line">    /bin/sh: mysql_config: command not found</span><br><span class="line">    Traceback (most recent call last):</span><br><span class="line">      File &quot;&lt;string&gt;&quot;, line 1, in &lt;module&gt;</span><br><span class="line">      File &quot;/private/var/folders/50/kvjmxf5d2hg0rq39dlmsw7m80000gn/T/pip-install-g7bdz3of/mysqlclient/setup.py&quot;, line 18, in &lt;module&gt;</span><br><span class="line">        metadata, options = get_config()</span><br><span class="line">      File &quot;/private/var/folders/50/kvjmxf5d2hg0rq39dlmsw7m80000gn/T/pip-install-g7bdz3of/mysqlclient/setup_posix.py&quot;, line 53, in get_config</span><br><span class="line">        libs = mysql_config(&quot;libs_r&quot;)</span><br><span class="line">      File &quot;/private/var/folders/50/kvjmxf5d2hg0rq39dlmsw7m80000gn/T/pip-install-g7bdz3of/mysqlclient/setup_posix.py&quot;, line 28, in mysql_config</span><br><span class="line">        raise EnvironmentError(&quot;%s not found&quot; % (mysql_config.path,))</span><br><span class="line">    OSError: mysql_config not found</span><br><span class="line"></span><br><span class="line">    ----------------------------------------</span><br><span class="line">Command &quot;python setup.py egg_info&quot; failed with error code 1 in /private/var/folders/50/kvjmxf5d2hg0rq39dlmsw7m80000gn/T/pip-install-g7bdz3of/mysqlclient/</span><br><span class="line">You are using pip version 10.0.1, however version 18.1 is available.</span><br><span class="line">You should consider upgrading via the &apos;pip install --upgrade pip&apos; command.</span><br><span class="line">(venv) zhaohandeMacBook-Pro:bhjd_newmanager zhaohan$</span><br></pre></td></tr></table></figure>
<p>注意到这句话:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ou are using pip version 10.0.1, however version 18.1 is available.</span><br><span class="line">You should consider upgrading via the &apos;pip install --upgrade pip&apos; command.</span><br></pre></td></tr></table></figure></p>
<p>忍不住手痒痒,升级了一把。</p>
<p>想看看新版的pip是否可以帮我解决这个问题，重新执行了一遍命令，还是报同样的错误。继续排查错误吧。</p>
<p>就把 /bin/sh: mysql_config: command not found 拿去搜一下。</p>
<p>顺藤摸瓜，找到了这篇文章<a href="https://www.easegamer.com/?p=545" target="_blank" rel="noopener">https://www.easegamer.com/?p=545</a></p>
<p>他前面说要安装mysql-connector-c，不记得我是否安装过，就无脑再装一遍好了，如果已经安装了，应该会提示我。</p>
<p>再执行 pip install mysqlclient，错误变了</p>
<p><img src="http://qnfile.devzhao.com/blog/2018-11-06-053742.png" alt=""></p>
<p>按照文章中的方式看看mysql_config</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">$ cd /usr/local/Cellar/mysql-connector-c/6.1.11/bin</span><br><span class="line"></span><br><span class="line"># 修改前先备份</span><br><span class="line">$ cp  mysql_config mysql_config.backup</span><br><span class="line"></span><br><span class="line"># 使用vi修改配置文件</span><br><span class="line">$ sudo vim mysql_config</span><br><span class="line"></span><br><span class="line"># 114 gg跳转到 114行</span><br><span class="line"></span><br><span class="line">将</span><br><span class="line">&gt; # Create options</span><br><span class="line">&gt; libs=&quot;-L$pkglibdir&quot;</span><br><span class="line">&gt; libs=&quot;$libs -l &quot;</span><br><span class="line"></span><br><span class="line">替换为</span><br><span class="line"></span><br><span class="line">&gt; # Create options</span><br><span class="line">&gt; libs=&quot;-L$pkglibdir&quot;</span><br><span class="line">&gt; libs=&quot;$libs -lmysqlclient -lssl -lcrypto&quot;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">然后保存即可。</span><br><span class="line"></span><br><span class="line">#  然后重新运行mysqlclient安装命令，之后一切顺利，大功告成</span><br><span class="line">pip install mysqlclient</span><br></pre></td></tr></table></figure>
<p>mysqlclient问题解决！</p>
<p>文章后面还提到另外一个问题，是连接mysql思维时候可能会出现的，等后面使用的时候遇到再说。</p>
<h5 id="测试Django使用mysql"><a href="#测试Django使用mysql" class="headerlink" title="测试Django使用mysql"></a>测试Django使用mysql</h5><p>继续按照<a href="https://www.cnblogs.com/yuyang26/p/7411269.html" target="_blank" rel="noopener">mysql 连接 django</a>的操作</p>
<ol>
<li>配置数据库连接</li>
</ol>
<p><img src="http://qnfile.devzhao.com/blog/2018-11-06-055345.png" alt=""></p>
<ol start="2">
<li>新建文件bhjd_newmanager/Api/models.py</li>
</ol>
<p>创建一些模型去加到数据库里</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">from django.db import models</span><br><span class="line"></span><br><span class="line"># Create your models here.</span><br><span class="line">class Category(models.Model):</span><br><span class="line">    cate_name=models.CharField(max_length=200)</span><br><span class="line"></span><br><span class="line">class news(models.Model):</span><br><span class="line">    n_title = models.CharField(max_length=200)</span><br><span class="line">    n_content = models.CharField(max_length=200)</span><br><span class="line">    n_is_publish = models.CharField(max_length=2)</span><br><span class="line">    n_category = models.CharField(max_length=2)</span><br></pre></td></tr></table></figure>
<p>calss  定义的类名将会是数据库对应的表名，属性对应字段，不过表明有所偏差，假如你的应用名是blog ,class名是Book, 创建的表则是blog_book   数据库不区分大小写</p>
<ol start="3">
<li>在配置文件settings.py 修改</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">INSTALLED_APPS = [</span><br><span class="line">    ...</span><br><span class="line">    &apos;Api&apos;,</span><br><span class="line">]</span><br></pre></td></tr></table></figure>
<blockquote>
<p>执行到这一步的时候，我已经不知道接下来该怎么办了，因为不理解稳重的Api.apps.BlogConfig的意思，再去找找其他的资料看有没有其他的发现,<br>在这篇文章<a href="https://www.cnblogs.com/stuqx/p/7127980.html里面发现，前面的Api应该是一个下属APP，而不是package这么简单，按照这篇文章的方法，创建一个下属APP，那么这里填这个下属APP的名字就行了" target="_blank" rel="noopener">https://www.cnblogs.com/stuqx/p/7127980.html里面发现，前面的Api应该是一个下属APP，而不是package这么简单，按照这篇文章的方法，创建一个下属APP，那么这里填这个下属APP的名字就行了</a></p>
</blockquote>
<ol start="4">
<li>将models.py中的数据库表结构同步到MYSQL中</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">$ python manage.py migrate #创建表结构</span><br><span class="line">$ python manage.py makemigrations Api #告诉django，Api中的表结构有更新</span><br><span class="line">$ python manage.py migrate Api  #执行Api中的表结构到mysql中</span><br></pre></td></tr></table></figure>
<p>执行完之后发现表已经同步到了数据库中</p>
<p><img src="http://qnfile.devzhao.com/blog/2018-11-06-063518.png" alt=""></p>
<p>这里担心一个问题：如果表中已经有数据了，我在项目中修改了表的结构，已经有的数据会不会丢失？</p>
<p>后面的测试就把代码放到view.py中去测试,比如：<br><img src="http://qnfile.devzhao.com/blog/2018-11-06-063954.png" alt=""></p>
<ol start="5">
<li>数据表操作</li>
</ol>
<ul>
<li>增</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">test1 = news(n_title=&apos;标题&apos;, n_content=&apos;内容&apos;, n_category=&apos;测试&apos;, n_is_publish=&apos;1&apos;)</span><br><span class="line">test1.save()</span><br></pre></td></tr></table></figure>
<ul>
<li>删</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">test1 = news.objects.get(id=1)</span><br><span class="line">test1.delete()</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">news.objects.filter(n_title=&apos;testname&apos;).delete()</span><br><span class="line">news.objects.all().delete()</span><br></pre></td></tr></table></figure>
<ul>
<li>改</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">test1 = news.objects.get(id=1)</span><br><span class="line">test1.n_title = &apos;book1&apos;</span><br><span class="line">test1.n_content = &apos;xxxxxxx&apos;</span><br><span class="line">test1.save</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">news.objects.filter(n_title=&apos;testname&apos;).update(n_content = &apos;xxxxxxx&apos;)</span><br><span class="line">news.objects.all().update(n_is_publish=&apos;1&apos;)</span><br></pre></td></tr></table></figure>
<ul>
<li>查</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">list = news.objects.all()</span><br><span class="line">for i in list:</span><br><span class="line">    print(i.n_title)</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">list = news.objects.filter(n_title=&apos;testname&apos;， n_is_publish=&apos;1&apos;)  #类似于SQL中的WHERE</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">list = news.objects.filter( n_title__contains=&apos;testuser&apos;)  #注意中间是双下划线，类似于SQL中的where fromuser like &quot;%testuser%&quot;</span><br><span class="line">#此外还有icontains(大小写无关的like),startswith和endswith, 还有range(SQL BETWEEN查询）</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">list = news.objects.get(n_title=&apos;testbookname&apos;)  #返回单条记录，不需要for直接list.bookname使用</span><br><span class="line">`</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">list = news.objects.filter().exclude().filter() #可无限嵌套</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">news.object.all()[:5]  #前5条记录</span><br><span class="line">news.object.order_by(n_title)[2:5]  #排序后的第3、4、5条记录</span><br><span class="line">news.object.order_by(n_title)[0]  #排序后的第1条记录</span><br><span class="line">news.object.order_by(n_title)[0:1].get() #排序后的第1条记录</span><br><span class="line">news.object.all()[:10:2]  #从第1条记录到第11条记录步长为2的数据集</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">__exact 精确等于 like ‘aaa’</span><br><span class="line">__iexact 精确等于 忽略大小写 ilike ‘aaa’</span><br><span class="line">__contains 包含 like ‘%aaa%’</span><br><span class="line">__icontains 包含 忽略大小写 ilike ‘%aaa%’，但是对于sqlite来说，contains的作用效果等同于icontains。</span><br><span class="line">__gt 大于</span><br><span class="line">__gte 大于等于</span><br><span class="line">__lt 小于</span><br><span class="line">__lte 小于等于</span><br><span class="line">__in 存在于一个list范围内</span><br><span class="line">__startswith 以…开头</span><br><span class="line">__istartswith 以…开头 忽略大小写</span><br><span class="line">__endswith 以…结尾</span><br><span class="line">__iendswith 以…结尾，忽略大小写</span><br><span class="line">__range 在…范围内</span><br><span class="line">__year 日期字段的年份</span><br><span class="line">__month 日期字段的月份</span><br><span class="line">__day 日期字段的日</span><br><span class="line">__isnull=True/False</span><br><span class="line">__isnull=True 与 __exact=None的区别</span><br></pre></td></tr></table></figure>
<h4 id="分页问题"><a href="#分页问题" class="headerlink" title="分页问题"></a>分页问题</h4><p>查询关键字 “Django 分页”</p>
<p><a href="http://www.cnblogs.com/kongzhagen/p/6640975.html" target="_blank" rel="noopener">http://www.cnblogs.com/kongzhagen/p/6640975.html</a></p>
<p>Django内置了分页功能。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">from django.core.paginator import Paginator</span><br><span class="line"></span><br><span class="line">...</span><br><span class="line"></span><br><span class="line">list = news.objects.all()</span><br><span class="line"></span><br><span class="line"># 分页器，前面是总共的元素，limit是每页的元素个数</span><br><span class="line">paginator = Paginator(list, limit)</span><br><span class="line">print(&apos;页码数量&apos;, paginator.num_pages)</span><br><span class="line"></span><br><span class="line"># 从页面获取页数信息，这里是获取？后参数page的value,</span><br><span class="line"># 可以看到get后的‘page’并不是我们定义的，而是我们获取的</span><br><span class="line"># 它的值就是个int</span><br><span class="line">page = request.GET.get(&apos;page&apos;, 1)</span><br><span class="line"></span><br><span class="line"># 显示某‘page’页面的信息</span><br><span class="line">loaded = paginator.page(page)</span><br><span class="line"></span><br><span class="line"># print(&apos;这里是loaded&apos;, loaded)</span><br><span class="line">print(&apos;page_range&apos;, paginator.page_range)</span><br><span class="line"></span><br><span class="line">pageobject_list = loaded.object_list</span><br><span class="line">for i in pageobject_list:</span><br><span class="line">    print(i.n_title)</span><br><span class="line"></span><br><span class="line">...</span><br></pre></td></tr></table></figure>
<p><a href="http://127.0.0.1:8000/pagination_job/?page=2" target="_blank" rel="noopener">http://127.0.0.1:8000/pagination_job/?page=2</a></p>
<h4 id="Django数据库连接池"><a href="#Django数据库连接池" class="headerlink" title="Django数据库连接池"></a>Django数据库连接池</h4><p><a href="http://python.jobbole.com/85997/" target="_blank" rel="noopener">http://python.jobbole.com/85997/</a></p>
<p>Python就没有数据库连接池 😝😝😝😝😝😝</p>
<h3 id="后台的管理的权限怎么办"><a href="#后台的管理的权限怎么办" class="headerlink" title="后台的管理的权限怎么办"></a>后台的管理的权限怎么办</h3><h4 id="Django-admin"><a href="#Django-admin" class="headerlink" title="Django admin"></a>Django admin</h4><p>什么？后台管理？你可能还没听说过Django自带了一套后台管理吧？</p>
<p><a href="https://code.ziqiangxuetang.com/django/django-admin.html" target="_blank" rel="noopener">https://code.ziqiangxuetang.com/django/django-admin.html</a></p>
<p>如果你的需求不是很复杂，那就别太多事了。</p>
<h4 id="session"><a href="#session" class="headerlink" title="session"></a>session</h4><p>首先想到的就是session,以下是session的使用方法。</p>
<p>但是如果网站是前后端分离的，session就不好使了，就要考虑token了。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">#1、生成随机字符串（sessionID）</span><br><span class="line">#2、通过cookie发送给客户端</span><br><span class="line">#3、服务端保存&#123;zhanggen随机字符串:&#123;&apos;name&apos;:&apos;zhanggen&apos;.&apos;email&apos;:&apos;zhanggen@le.com&apos;&#125;&#125;</span><br><span class="line">request.session[&apos;name&apos;]=obj.username #在Django 中一句话搞定</span><br><span class="line">request.session[&apos;email&apos;] = &apos;zhanggen@le.com&apos;</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">#1、获取客户端的 sessionID</span><br><span class="line">#2、在服务端查找是否存在 这个sessionID</span><br><span class="line">#3、在服务端查看对应的key sessionID键的值中是否有name（有值就是登录过了！！）</span><br><span class="line">v=request.session.get(&apos;name&apos;)</span><br><span class="line">print(v)</span><br><span class="line">if v:</span><br><span class="line">    return render(request,&apos;index.html&apos;,&#123;&apos;msg&apos;:v&#125;)</span><br><span class="line">else:return redirect(&apos;/login/&apos;)</span><br></pre></td></tr></table></figure>
<h4 id="token"><a href="#token" class="headerlink" title="token"></a>token</h4><p>在spring开发接口的时候，使用jwt做token，那么看看有没有python版本的。</p>
<p>关键字“Django jwt”</p>
<p>还真有 <a href="https://blog.csdn.net/Odyssues_lee/article/details/80837076" target="_blank" rel="noopener">https://blog.csdn.net/Odyssues_lee/article/details/80837076</a></p>
<p><a href="https://segmentfault.com/a/1190000010312468" target="_blank" rel="noopener">https://segmentfault.com/a/1190000010312468</a></p>
<p>下面是简单的使用jwt</p>
<p> 生成token</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">import jwt</span><br><span class="line"></span><br><span class="line">payload = &#123;</span><br><span class="line">    &quot;iat&quot;: int(time.time()),</span><br><span class="line">    &quot;exp&quot;: int(time.time()) + 86400 * 7,</span><br><span class="line">    &quot;username&quot;: username,</span><br><span class="line">    &quot;scopes&quot;: [&apos;open&apos;]</span><br><span class="line">&#125;</span><br><span class="line">token = jwt.encode(payload, &apos;secret&apos;, algorithm=&apos;HS256&apos;)</span><br><span class="line"></span><br><span class="line">print(&apos;token&apos;, token)</span><br></pre></td></tr></table></figure>
<p>验证token</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">def verify_bearer_token(token):</span><br><span class="line">    #  如果在生成token的时候使用了aud参数，那么校验的时候也需要添加此参数</span><br><span class="line">    payload = jwt.decode(token, &apos;secret&apos;, audience=&apos;www.gusibi.com&apos;, algorithms=[&apos;HS256&apos;])</span><br><span class="line">    if payload:</span><br><span class="line">        return True, token</span><br><span class="line">    return False, token</span><br></pre></td></tr></table></figure>
<p>这里就不说怎么安装和配置了。因为我要做的系统很简单，Django admin就能满足。</p>
<h2 id="结尾"><a href="#结尾" class="headerlink" title="结尾"></a>结尾</h2><p>这个小项目，从完全不懂python到此，用了三个小时。</p>
<p>有些事情只要你想做，其实是可以做到的。</p>

      
    </div>

    

    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持分享输出，感谢你的支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="zhaohan 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="zhaohan 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>zhaohan</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://devzhao.com/post/f7443a5f.html" title="3个小时零Python基础搭建Django项目">https://devzhao.com/post/f7443a5f.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/笔记/" rel="tag"># 笔记</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/post/1e21d5b5.html" rel="next" title="产品经理定义需求优先级的四种方法">
                <i class="fa fa-chevron-left"></i> 产品经理定义需求优先级的四种方法
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/post/93494858.html" rel="prev" title="自动化将hexo部署到oss">
                自动化将hexo部署到oss <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="http://qnfile.devzhao.com/blog/2018-10-12-125720.jpg#/images/avatar.gif"
                alt="zhaohan" />
            
              <p class="site-author-name" itemprop="name">zhaohan</p>
              <p class="site-description motion-element" itemprop="description">教，是最好的学</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">148</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">33</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">29</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#需求分析"><span class="nav-number">1.</span> <span class="nav-text">需求分析</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#技术选型"><span class="nav-number">2.</span> <span class="nav-text">技术选型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#了解主流的python框架"><span class="nav-number">2.1.</span> <span class="nav-text">了解主流的python框架</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Django"><span class="nav-number">3.</span> <span class="nav-text">Django</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Django实现restful"><span class="nav-number">3.1.</span> <span class="nav-text">Django实现restful</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#PyCharm"><span class="nav-number">3.2.</span> <span class="nav-text">PyCharm</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Hello-world"><span class="nav-number">3.3.</span> <span class="nav-text">Hello world</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#项目搭建"><span class="nav-number">4.</span> <span class="nav-text">项目搭建</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#restfull"><span class="nav-number">4.1.</span> <span class="nav-text">restfull</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#如何连数据库，处理连接池问题"><span class="nav-number">4.2.</span> <span class="nav-text">如何连数据库，处理连接池问题</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Django使用mysql"><span class="nav-number">4.2.1.</span> <span class="nav-text">Django使用mysql</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#安装mysqlclient"><span class="nav-number">4.2.1.1.</span> <span class="nav-text">安装mysqlclient</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#测试Django使用mysql"><span class="nav-number">4.2.1.2.</span> <span class="nav-text">测试Django使用mysql</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#分页问题"><span class="nav-number">4.2.2.</span> <span class="nav-text">分页问题</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Django数据库连接池"><span class="nav-number">4.2.3.</span> <span class="nav-text">Django数据库连接池</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#后台的管理的权限怎么办"><span class="nav-number">4.3.</span> <span class="nav-text">后台的管理的权限怎么办</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Django-admin"><span class="nav-number">4.3.1.</span> <span class="nav-text">Django admin</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#session"><span class="nav-number">4.3.2.</span> <span class="nav-text">session</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#token"><span class="nav-number">4.3.3.</span> <span class="nav-text">token</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#结尾"><span class="nav-number">5.</span> <span class="nav-text">结尾</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zhaohan</span>

  

  
</div>


  










        
<div class="busuanzi-count">
  <!--<script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>-->

  <script async src="//cdn.busuanzi.ibruce.info/cdn/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <!-- <i class="fa fa-user-circle"></i> -->
      <i>已有</i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      <i>位访客浏览过此网站</i>
    </span>
  

  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
	
    

    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.2"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.2"></script>



  



  








  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  
  
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick';
    guest = guest.split(',').filter(function (item) {
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: true,
        notify: false,
        appId: 'z99UqRJEaGqxYLDPSPSx5jih-gzGzoHsz',
        appKey: 'N7MTJbRdufk8MAg3yeK6Gs9U',
        placeholder: '说点什么吧...',
        avatar:'mm',
        meta:guest,
        pageSize:'10' || 10,
        visitor: false
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script>
    
    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function ({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
            Counter('put', `/classes/Counter/${counter.objectId}`, JSON.stringify({ time: { "__op":"Increment", "amount":1 } }))
            
            .done(function () {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(counter.time + 1);
            })
            
            .fail(function ({ responseJSON }) {
                console.log('Failed to save Visitor num, with error message: ' + responseJSON.error);
            })
          } else {
            
              Counter('post', '/classes/Counter', JSON.stringify({ title: title, url: url, time: 1}))
                .done(function () {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(1);
                })
                .fail(function () {
                  console.log('Failed to create');
                });
            
          }
        })
      .fail(function ({ responseJSON }) {
        console.log('LeanCloud Counter Error:' + responseJSON.code + " " + responseJSON.error);
      });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + "z99UqRJEaGqxYLDPSPSx5jih-gzGzoHsz")
        .done(function ({ api_server }) {
          var Counter = function (method, url, data) {
            return $.ajax({
              method: method,
              url: `https://${api_server}/1.1${url}`,
              headers: {
                'X-LC-Id': "z99UqRJEaGqxYLDPSPSx5jih-gzGzoHsz",
                'X-LC-Key': "N7MTJbRdufk8MAg3yeK6Gs9U",
                'Content-Type': 'application/json',
              },
              data: data,
            });
          };
          
          addCount(Counter);
          
        })
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  
  

  

  

  

  

  

</body>
</html>
